/**
 * @file server.c 服务器端主函数
 *  
 * @author pzk (1528089905@qq.com)
 * @brief 
 * @version 1.5
 * @date 2025-8-25
 * 
 * @copyright copyright (c) 2025
 */
#include "server.h"

int user_id_min = 1000;       // 用户ID起始值
int user_count = 0;           // 总用户数
pthread_mutex_t users_mutex,online_mutex;  // 互斥锁，用于保护用户数据
pthread_t pthid;              // 线程ID
int server_sock;              // 服务器套接字
node_t *users_list = NULL;    // 用户链表
node_t *online_list = NULL;   // 在线用户链表


int main() 
{
    // 初始化服务器
    struct sockaddr_in from;
    socklen_t len = sizeof(from);
    int fd;

    init_server();
    
    // 显示服务器启动信息
    printf("═════ EasyChat Server ═════\n");
    printf("[SERVER] Server port: %d\n", PORT);
    printf("[SERVER] Wait client to connnet...\n");

    while(1)
    {
        fd = accept(server_sock, (struct sockaddr *)&from, &len);
	    SYSERR2(fd, ==, -1, "Failed to accept connection", return -1);
        printf("[SERVER] %s:%d connected successfully\n", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
        
        // 动态分配内存存储fd，避免线程间竞争
        int *client_fd_ptr = malloc(sizeof(int));
        *client_fd_ptr = fd;
        pthread_create(&pthid, NULL, handle_client, client_fd_ptr);
        pthread_detach(pthid);  // 分离线程，自动释放资源
    }

	close(fd);
	close(server_sock);
	return 0;
}